# _*_ coding utf-8 _*_
# FILENAME：BaseQueryWindow.py
# DESCRIPTION: 查询界面基类
# AUTH: jarvis zhang
# DATE: 2022/6/12 4:49 下午
import os

from PyQt5.Qt import *
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import *
import qtawesome as qta
from components.BaseMainWindow import BaseMainWindow


class BaseQueryWindow(BaseMainWindow):
    # 当前页
    __currentPage = 1
    # 总页数
    __totalPage = 0
    # 总记录数
    __totalRecrodCount = 0
    # 每页显示记录数
    __PageRecordCount = 10

    def __init__(self):
        super(BaseQueryWindow, self).__init__()
        self.setWindowModality(Qt.NonModal)
        #  tableView对象
        self.tableView = QTableView()
        self.dataModel = QStandardItemModel()
        self.tableView.setModel(self.dataModel)
        #  初始化布局
        self.__init_ui(self)
        self.PageRecordCount = 10  # 每页显示记录数
        self.setTableViewProperties()  # 表格默认属性
        self.__init_pagePanel()  # 初始化分页面板
        # 信号槽连接
        self.prevButton.clicked.connect(self.__onPrevButtonClick)
        self.nextButton.clicked.connect(self.__onNextButtonClick)
        self.switchPageButton.clicked.connect(self.__onSwitchPageButtonClick)

    def show(self):
        super(BaseQueryWindow, self).show()

    def close(self):
        self.dataModel.clear()
        self.tableView.close()
        super(BaseQueryWindow, self).close()

    #  布局
    def __init_ui(self, MainWindow):
        self.cwd = os.getcwd()  # 文件路径

        # toolbar
        self.toolBar = QToolBar(MainWindow)
        self.toolBar.setObjectName("toolbar")
        self.btn_add = QToolButton()
        self.btn_add.setText("新增")
        self.btn_add.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_add.setIcon(qta.icon('ri.file-add-line'))  # 设置图标

        self.btn_log = QToolButton()
        self.btn_log.setText("上传日志")
        self.btn_log.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_log.setIcon(qta.icon('ri.file-upload-line'))  # 设置图标

        self.btn_cal_log = QToolButton()
        self.btn_cal_log.setText("运算日志")
        self.btn_cal_log.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_cal_log.setIcon(qta.icon('ri.calculator-line'))  # 设置图标

        self.btn_download_log = QToolButton()
        self.btn_download_log.setText("下载日志")
        self.btn_download_log.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_download_log.setIcon(qta.icon('ri.file-download-line'))  # 设置图标

        self.btn_refresh = QToolButton()
        self.btn_refresh.setText("刷新")
        self.btn_refresh.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_refresh.setIcon(qta.icon('ri.refresh-line'))  # 设置图标

        self.btn_close = QToolButton()
        self.btn_close.setText("关闭")
        self.btn_close.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.btn_close.setIcon(qta.icon('ri.door-closed-line'))  # 设置图标

        self.toolBar.addWidget(self.btn_add)
        self.toolBar.addWidget(self.btn_log)
        self.toolBar.addWidget(self.btn_cal_log)
        self.toolBar.addWidget(self.btn_download_log)
        self.toolBar.addWidget(self.btn_refresh)
        self.toolBar.addWidget(self.btn_close)
        MainWindow.addToolBar(Qt.TopToolBarArea, self.toolBar)

        # 查询布局
        queryLayout = QHBoxLayout()
        self.queryWidget = QWidget()
        self.setQuertLayout(self, queryLayout)
        self.queryWidget.setLayout(queryLayout)
        # 操作布局
        operatorLayout = QHBoxLayout()
        self.prevButton = QPushButton("前一页")
        self.nextButton = QPushButton("后一页")
        self.switchPageButton = QPushButton("GO")
        self.switchPageLineEdit = QLineEdit()
        self.switchPageLineEdit.setFixedWidth(40)

        switchPage = QLabel('转到第')
        page = QLabel('页')
        operatorLayout.addWidget(self.prevButton)
        operatorLayout.addWidget(self.nextButton)
        operatorLayout.addWidget(switchPage)
        operatorLayout.addWidget(self.switchPageLineEdit)
        operatorLayout.addWidget(page)
        operatorLayout.addWidget(self.switchPageButton)
        operatorLayout.addWidget(QSplitter())

        # 状态布局
        statusLayout = QHBoxLayout()
        self.totalPageLabel = QLabel()
        self.totalPageLabel.setFixedWidth(70)
        self.currentPageLabel = QLabel()
        self.currentPageLabel.setFixedWidth(70)

        self.totalRecordLabel = QLabel()
        self.totalRecordLabel.setFixedWidth(70)

        statusLayout.addWidget(self.totalPageLabel)
        statusLayout.addWidget(self.totalRecordLabel)
        statusLayout.addWidget(self.currentPageLabel)
        statusLayout.addWidget(QSplitter())
        operatorWidget = QWidget()
        operatorWidget.setLayout(operatorLayout)
        statusLayout.addWidget(operatorWidget)

        # 校验器
        self.switchPageLineEdit.setValidator(QIntValidator(self))

        # 创建界面
        self.mainLayout = QVBoxLayout(self)
        # mainLayout.addLayout(operatorLayout)
        self.mainLayout.addWidget(self.queryWidget)
        self.mainLayout.addWidget(self.tableView)
        self.mainLayout.addLayout(statusLayout)
        # self.setLayout(self.mainLayout)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.centralwidget.setLayout(self.mainLayout)
        self.setCentralWidget(self.centralwidget)

    # 查询布局
    def setQuertLayout(self, parent=None, queryLayout=None):
        lab_no = QLabel("编号:")
        lab_no.setFixedWidth(30)
        self.lab_vension = QLabel("版本:")
        self.lab_vension.setFixedWidth(30)
        self.edit_no = QLineEdit()
        self.edit_no.setFixedWidth(100)
        self.edit_no.setPlaceholderText("请输入编号")
        self.edit_vension = QLineEdit()
        self.edit_vension.setFixedWidth(200)
        self.edit_vension.setPlaceholderText("请输入版本")
        btnQuery = QPushButton("查询")
        btnQuery.setFixedWidth(80)
        btnQuery.clicked.connect(self.query_click)

        queryLayout.addWidget(lab_no)
        queryLayout.addWidget(self.edit_no)
        queryLayout.addWidget(self.lab_vension)
        queryLayout.addWidget(self.edit_vension)
        queryLayout.addWidget(btnQuery)
        queryLayout.addStretch(2)

    #  设置tableView属性
    def setTableViewProperties(self):
        # 设置表格属性
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中整行
        self.tableView.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中一行
        # 表格宽度的自适应调整
        # self.tableView.horizontalHeader().setStretchLastSection(True)
        # self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自动拉伸，充满界面

    # 初始化分页面板
    def __init_pagePanel(self):
        # 刷新状态
        self.__updateStatus()
        # 设置总页数文本
        self.__setTotalPageLabel()
        # 设置总记录数
        self.__setTotalRecordLabel()

    # 得到记录数
    def setTotalRecordCount(self, count):
        self.__totalRecrodCount = count
        # 设置页面总数
        self.__setPageCount()
        # 初始化分页面板
        self.__init_pagePanel()

    # 得到页数
    def __setPageCount(self):
        if self.__totalRecrodCount % self.PageRecordCount == 0:
            pageTotal = (self.__totalRecrodCount / self.PageRecordCount)
        else:
            pageTotal = (self.__totalRecrodCount / self.PageRecordCount + 1)
        self.__totalPage = pageTotal

    # 记录查询
    def recordQuery(self, limitIndex):
        pass

    # 刷新状态
    def __updateStatus(self):
        szCurrentText = ('当前第 %d 页' % self.__currentPage)
        self.currentPageLabel.setText(szCurrentText)
        # 设置按钮是否可用
        if self.__currentPage <= 1:
            self.prevButton.setEnabled(False)
        else:
            self.prevButton.setEnabled(True)

        if self.__currentPage > self.__totalPage - 1:
            self.nextButton.setEnabled(False)
        else:
            self.nextButton.setEnabled(True)

    # 设置总页数文本
    def __setTotalPageLabel(self):
        szPageCountText = ('总共 %d 页' % self.__totalPage)
        self.totalPageLabel.setText(szPageCountText)

    # 设置总记录数
    def __setTotalRecordLabel(self):
        szTotalRecordText = ('共 %d 条' % self.__totalRecrodCount)
        self.totalRecordLabel.setText(szTotalRecordText)

    # 前一页被按下
    def __onPrevButtonClick(self):
        limitIndex = (self.__currentPage - 2) * self.__PageRecordCount
        self.recordQuery(limitIndex)
        self.__currentPage -= 1
        self.__updateStatus()

    # 后一页被按下
    def __onNextButtonClick(self):
        limitIndex = self.__currentPage * self.__PageRecordCount
        self.recordQuery(limitIndex)
        self.__currentPage += 1
        self.__updateStatus()

    # 转到页按钮被按下
    def __onSwitchPageButtonClick(self):
        #  得到输入的字符串
        szText = self.switchPageLineEdit.text()
        if not szText:
            QMessageBox.information(self, '提示', "请输入指定的页面")
            return
        # 得到页数
        pageIndex = int(szText)
        # 判断是否有指定页
        if pageIndex > self.__totalPage or pageIndex < 1:
            QMessageBox.information(self, '提示', "没有指定的页面,重新输入")
            return
        # 得到查询起始行号
        limitIndex = (pageIndex - 1) * self.__PageRecordCount
        # 记录查询
        self.recordQuery(limitIndex)
        # 设置当前页
        self.__currentPage = pageIndex
        # 刷新状态
        self.__updateStatus()

    # 刷新页面
    def refresh(self):
        # 查询
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        index = (self.__currentPage - 1) * self.__PageRecordCount
        if index == 0 or (index + 1) < total:
            # 当前页
            self.recordQuery(index)  # page
        else:
            # 上一页
            self.recordQuery(index - self.__PageRecordCount)  # page
            # 设置页数
            self.__currentPage = self.__currentPage - 1
            # 刷新状态
            self.__updateStatus()


    def query_click(self):
        total = self.query_total(self.edit_vension.text())
        self.setTotalRecordCount(total)  # 总量
        self.recordQuery(0)

    def edit_click(self):
        pass

    def upload_click(self):
        pass

    def cal_click(self):
        pass

    def view_click(self):
        pass

    def del_click(self):
        pass

    def download_click(self):
        pass


#  自定义ItemDelegate代理，在列表中显示按钮
class CustomButtonDelegate(QItemDelegate):
    #  定义按钮隐藏数组，[btnEdit, btnUpload, btnCal, btnView, btnDel]
    __isHides = []

    def __init__(self, parent=None, isHides=[]): #  isHide数组代表下面的5个按钮，根据下标值是否True或者False控制按钮是否展示
        super(CustomButtonDelegate, self).__init__(parent)
        self.__isHides = isHides

    def __setIsHide(self, btn=None, isHide=False):
        btn.setHidden(isHide)

    def paint(self, painter, option, index):
        if not self.parent().tableView.indexWidget(index):
            '''定义按钮'''
            btn_edit = QPushButton(
                self.tr('编辑'),
                self.parent(),
                clicked=self.parent().edit_click
            )
            # btn_edit.setStyleSheet('''
            #                         color: #fff;
            #                                   background-color : #6c757d;
            #                                   ''')

            btn_upload = QPushButton(
                self.tr('上传'),
                self.parent(),
                clicked=self.parent().upload_click
            )
            # btn_upload.setStyleSheet('''
            #                                             color: #fff;
            #                                               background-color : #17a2b8;
            #                                               ''')

            btn_cal = QPushButton(
                self.tr('运算'),
                self.parent(),
                clicked=self.parent().cal_click
            )
            # btn_upload.setStyleSheet('''
            #                                             color: #fff;
            #                                               background-color : #17a2b8;
            #                                               ''')

            btn_view = QPushButton(
                self.tr('查看'),
                self.parent(),
                clicked=self.parent().view_click
            )
            # btn_upload.setStyleSheet('''
            #                                             color: #fff;
            #                                               background-color : #17a2b8;
            #                                               ''')

            btn_del = QPushButton(
                self.tr('删除'),
                self.parent(),
                clicked=self.parent().del_click
            )
            # btn_del.setStyleSheet('''
            #                     color: #fff;
            #                       background-color : #dc3545;
            #                       ''')

            btn_download = QPushButton(
                self.tr('下载'),
                self.parent(),
                clicked=self.parent().download_click
            )
            btn_download.setHidden(True)
            # btn_del.setStyleSheet('''
            #                     color: #fff;
            #                       background-color : #dc3545;
            #                       ''')
            '''设置是否隐藏'''
            self.__setIsHide(btn_edit, self.__isHides[0])
            self.__setIsHide(btn_upload, self.__isHides[1])
            self.__setIsHide(btn_cal, self.__isHides[2])
            self.__setIsHide(btn_view, self.__isHides[3])
            self.__setIsHide(btn_del, self.__isHides[4])
            self.__setIsHide(btn_download, self.__isHides[5])
            #  设置index
            btn_edit.index = [index.row(), index.column()]
            btn_upload.index = [index.row(), index.column()]
            btn_cal.index = [index.row(), index.column()]
            btn_view.index = [index.row(), index.column()]
            btn_del.index = [index.row(), index.column()]
            btn_download.index = [index.row(), index.column()]
            # 布局
            h_box_layout = QHBoxLayout()
            h_box_layout.addWidget(btn_edit)
            h_box_layout.addWidget(btn_upload)
            h_box_layout.addWidget(btn_cal)
            h_box_layout.addWidget(btn_view)
            h_box_layout.addWidget(btn_del)
            h_box_layout.addWidget(btn_download)
            h_box_layout.setContentsMargins(0, 0, 0, 0)
            h_box_layout.setAlignment(Qt.AlignCenter)
            widget = QWidget()
            widget.setLayout(h_box_layout)
            self.parent().tableView.setIndexWidget(
                index,
                widget
            )